package com.jdy.haoduoai.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import com.jdy.haoduoai.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

//import com.jdy.haoduoai.R;

/**
 * 
 * @author hf
 * 
 */
public class CardCell extends View {

  static final float STEP = 5;
  private String text = "0";
  private String preText = "0";
  private Paint paint;
  private float startH = 0;
  private int imgvW;
  private int imgvH;
  private float textBaseY;
  private float textX;

  public CardCell(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
  }

  public CardCell(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  public CardCell(Context context) {
    super(context);
    init();
  }

  private void init() {
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.BLACK);
    paint.setTextAlign(Align.CENTER);
    paint.setTextSize(Tools.getPixelByDip(getContext(), 16));
    Drawable dr = getContext().getResources().getDrawable(R.drawable.num_bg);
    imgvW = dr.getIntrinsicWidth();
    imgvH = dr.getIntrinsicHeight();

    FontMetrics fontMetrics = paint.getFontMetrics();
    float fontHeight = fontMetrics.bottom - fontMetrics.top;
    textBaseY = imgvH - (imgvH - fontHeight) / 2 - fontMetrics.bottom;
    textX = imgvW / 2;

  }

  public void setText(String text) {
    if (!text.equals(this.text)) {
      startH = textBaseY;
      this.preText = this.text;
      this.text = text;
      postInvalidate();
    }

  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(imgvW, imgvH);
  }

  @Override
  protected void onLayout(boolean changed, int left, int top, int right,
      int bottom) {
    super.onLayout(changed, left, top, right, bottom);
  }

  private Runnable task = new Runnable() {

    @Override
    public void run() {
      if (startH > 0) {
        startH -= STEP;
        startH = startH < 0 ? 0 : startH;
        postInvalidate();
      }

    }
  };

  @Override
  protected void onDraw(Canvas canvas) {
    if (isInEditMode()) {
      return;
    }
    super.onDraw(canvas);
    canvas.drawText(text, textX, textBaseY + startH, paint);
    canvas.drawText(preText, textX, startH - 1, paint);

    postDelayed(task, 50);
  }

}
